package com.jewelry.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jewelry.common.config.ConfigManager;
import com.jewelry.common.util.Constants;

public class FileUploadAction extends HttpAction {

	private static final long serialVersionUID = 2813819507776329774L;
	
	private static Logger logger = LoggerFactory.getLogger(FileUploadAction.class);

	private File file;
	private String fileFileName;
	private String fileFileContentType;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileFileContentType() {
		return fileFileContentType;
	}

	public void setFileFileContentType(String fileFileContentType) {
		this.fileFileContentType = fileFileContentType;
	}

	public String upload()throws Exception {
		String path = ConfigManager.getConfigString(Constants.RESPATH_CONFIG_NAME);
		String resuri = ConfigManager.getConfigString(Constants.RESURI_CONFIG_NAME);
		
		
		
		File temp = new File(path);
		if (!temp.exists()) {
			temp.mkdirs();
		}
		
		int index = fileFileName.lastIndexOf(".");
		String extName = fileFileName.substring(index+1);
		
		if (!extName.equalsIgnoreCase("jpg") && !extName.equalsIgnoreCase("png")) {
			message = "对不起,你上传的文件格式不符合要求!!!";
			return message;
		}
		
		InputStream is = null;
		OutputStream out = null;
		File f = getFile();
		try {
			is = new FileInputStream(f);
			out = new FileOutputStream(path + File.separator
					+ getFileFileName());

			byte[] buf = new byte[1024];
			int length = 0;
			while ((length = is.read(buf)) != -1) {
				out.write(buf, 0, length);
			}
			out.flush();
			message = resuri + File.separator + getFileFileName();
		} catch (Exception e) {
			logger.error("File upload Failed!",e);
			message = "对不起,文件上传失败了!!!!";
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
		
		PrintWriter writer = httpResponse.getWriter();
		writer.write(message);
		writer.flush();
		writer.close();
		
		return SUCCESS;
	}

}
